import { Component, OnInit,ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpRequest } from "../../../../service/httpRequest";
import { NotiService } from "../../../../service/noti.service";
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';
import { FileLoader } from "../../../../service/fileLoader";
import { GlobalVariable } from '../../../../global.config';
import { ModalDirective } from 'ng2-bootstrap/modal';

declare let $:any;
@Component({
  selector: 'app-single-monitor-united1',
  templateUrl: './single-monitor-united1.component.html',
  styleUrls: ['./single-monitor-united1.component.css']
})
export class SingleMonitorUnited1Component implements OnInit {
  deviceId:string = '';
  chart1:any;
  chart2:any;
  chart3:any;
  private gizwitsNotiWs:any;
  devinfoData:any;  
  private eventType = ['device.status.kv'];
  propertyData:any;
  public tdata=[];
  public tmdata=[];
  @ViewChild('myModal') public myModal:ModalDirective;
  model:any = {begintime:'',endtime:''};
  constructor(private activeRoute:ActivatedRoute,private fileLoader:FileLoader,private httpRequest:HttpRequest,private noti:NotiService,private http:Http) { }

  ngOnInit() {
    this.fileLoader.LoadFileList(['assets/js/button.js'], function(){});
    this.activeRoute.params.subscribe(
      params=>{
        this.deviceId = params['deviceId'].replace('|','/');

        let p = this.deviceId.split('/');
        this.gizwitsNotiWs = this.noti.init(p[0].toLocaleLowerCase(),[p[1]],this.eventType,this.onEvent,this);
        this.gizwitsNotiWs.connect();
        this.initChart();
      }
    );
    this.getdevinfo();
    this.getProperty();
    this.initDatePicker();   


  }

  change(i){
    let cboxs = $('.xx-box');
    if(i >= cboxs.length) return ;
    $.each(cboxs,function(j,n){
      $(n).hide();
      $('.nav-title').eq(j).removeClass('active')
    });
    $('.xx-box').eq(i).show();
    $('.nav-title').eq(i).addClass('active');
  }

    //设备信息的获取
  getdevinfo(){

    this.httpRequest.sendGet('devices',{id:this.deviceId}).subscribe(res => {  
      //console.log(res)    
      this.devinfoData = res.result;    
      //console.log(this.devinfoData)  
    },err => console.log(err));
  }

  //数据点数据
  getProperty(){    
    this.httpRequest.sendGet('product/property/list/'+this.deviceId.split('/')[0]).subscribe(res => {      
      this.propertyData = res.result[0];   
      //console.log( this.propertyData)     
    },err => console.log(err));
  }



    //时间插件的初始化
  initDatePicker(){
    $(".form_datetime").datetimepicker({
            format: "yyyy-mm-dd hh:ii",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 30 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date()  
      });
      $(".form_datetime1").datetimepicker({
            format: "yyyy-mm-dd hh:00",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 365 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date(),        
            minView:1

      });
      $(".form_datetime2").datetimepicker({
            format: "yyyy-mm-dd hh:00",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 365 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date(),
            minView:1  
        });

        $(".form_datetimeout1").datetimepicker({
            format: "yyyy-mm-dd hh:00",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 365 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date(),        
            minView:1

      });

      $(".form_datetimeout2").datetimepicker({
            format: "yyyy-mm-dd hh:00",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 365 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date(),
            minView:1  
        });


    $('#qBeginTime').datetimepicker().on('changeDate',function(e){  
        var startTime = e.date;  
        $('#qEndTime').datetimepicker('setStartDate',startTime);  

    });  
      
    $('#qEndTime').datetimepicker().on('changeDate',function(e){  
        var endTime = e.date;  
        $('#qBeginTime').datetimepicker('setEndDate',endTime);  
    });


    $('#BeginTime').datetimepicker().on('changeDate',function(e){  
        var startTime = e.date;  
        $('#EndTime').datetimepicker('setStartDate',startTime);  

    });  
      
    $('#EndTime').datetimepicker().on('changeDate',function(e){  
        var endTime = e.date;  
        $('#BeginTime').datetimepicker('setEndDate',endTime);  
    });

  }

//查询历史数据
   public count = 0;   
   public selectedproperty:any = {};
   fn($event,property){  
     let checkbox = $event.target; 
        if (checkbox.checked) {
            this.count++;
            this.selectedproperty[property]=property;
        }else{
            this.count--;
            delete this.selectedproperty[property];
        }                
      if(this.count>5){
        alert("对不起，每次展示参数最多可以选择5个！");
        checkbox.checked = false;
        this.count=5;
      }             
    }         
public tldata:any;
    chosedparam(){       
      let properties = [];
      let btn = $("#myButton").button('loading') 
      for(let key in this.selectedproperty){
        properties.push(key)
      }
      let str = properties.join(',')
      let sdate = $('#stime').val(); 
      //console.log(sdate) 
       //console.log(str) 
      if(str!=''&&sdate!=''){
          let headers = new Headers();
          let authToken = localStorage.getItem("token");
          headers.append('Authorization', `token ${authToken}`);
          let options = new RequestOptions({ headers: headers }); 
          this.http.post('http://101.37.24.73:8088/gh30',{
            device_id:this.deviceId,
            sdate:sdate,
            parameter:str
          },options).subscribe(res=>{
            //console.log(res.json())            
            btn.button('reset');       
            let gh30data = res.json().result.aaData;         
            this.tdata = res.json().result.aaData;
            if(this.tdata.length==0){
              this.tldata = "所选参数在所选时间的前30分钟无数据。";
            }
            console.log(this.tldata)
            this.getqxdata('getqx',gh30data);
          },err=>{
            alert('查询失败');
            btn.button('reset'); 
          })    
          
      }else{
        alert('请选择参数或者时间');
        btn.button('reset'); 
      }
      // setTimeout(function () { },1000); 
     
  
    }  
    public tndata:any;
    chosedparam1(){
      let btn1 = $("#myButton1").button('loading') 
      let properties = [];      
      for(let key in this.selectedproperty){
        properties.push(key)
      }
      let str = properties.join(',')
      let sdate = $('#qBeginTime').val();
      let edate = $('#qEndTime').val();
      //console.log(sdate) 
       //console.log(str) 
      if(str!=''&&sdate!=''&&edate!=''){
          let headers = new Headers();
          let authToken = localStorage.getItem("token");
          headers.append('Authorization', `token ${authToken}`);
          let options = new RequestOptions({ headers: headers }); 
          this.http.post('http://101.37.24.73:8088/gh',{
            device_id:this.deviceId,
            sdate:sdate,   
            edate:edate,              
            parameter:str
          },options).subscribe(res=>{
            //console.log(res.json())
            btn1.button('reset');             
            let ghdata = res.json().result.aaData;
            this.tmdata = res.json().result.aaData;
            if(this.tmdata.length==0){
              this.tndata = "所选参数在所选时间段内无数据。"
            }
           
            this.getqxdata('getqx1',ghdata);

          },err=>{
            alert('查询失败');
            btn1.button('reset'); 
          })    
          
      }else{
        alert('请选择参数或者时间');
        btn1.button('reset'); 
      } 
   

     
}

getqxdata(id,data){
  $('#'+id).highcharts({
    chart: {
        type: 'spline'
    },
    title: {
        text: '参数的历史数据曲线'
    },
    
    xAxis: {
        type: 'datetime',
        labels: {
            overflow: 'justify'
        }
    },
    yAxis: {
        title: {
            text: '参数值'
        },
        minorGridLineWidth: 0,
        gridLineWidth: 0,
        alternateGridColor: null,
    
    },
    tooltip: {
        valueSuffix: ''
    },
    plotOptions: {
        spline: {
            lineWidth: 2,
            states: {
                hover: {
                    lineWidth: 3
                }
            },
            marker: {
                enabled: false
            },
            pointInterval: 3600000, // one hour
            // pointStart: Date.UTC(2015, 4, 31, 0, 0, 0)
        }
    },
    series: data,
    navigation: {
        menuItemStyle: {
            fontSize: '10px'
        }
    }
});
}


//导出历史数据
//30分钟
public out30d:any;
out30data(){
  let btn30 = $("#out30Button").button('loading');
  let properties = [];

  for(let key in this.selectedproperty){
    properties.push(key)
  }
  let str = properties.join(',')
  let sdate = $('#stime').val(); 
  if(str!=''&&sdate!=''){
    let headers = new Headers();
    let authToken = localStorage.getItem("token");
    headers.append('Authorization', `token ${authToken}`);
    let options = new RequestOptions({ headers: headers }); 
    this.http.post('http://101.37.24.73:8088/export/gh30',{
      device_id:this.deviceId,
      sdate:sdate,
      parameter:str
    },options).subscribe(res=>{
      //console.log(res.json());
      this.out30d = res.json().result.aaData.url;      
         
      btn30.button('reset');       
 
    },err=>{
      alert('查询失败');
      btn30.button('reset'); 
    })    
  }else{
      alert('请选择参数或者时间');
      btn30.button('reset'); 
  }
}
public  out60d:any;
out60data(){
  let btn60 = $("#out60Button").button('loading');
  let properties = [];

  for(let key in this.selectedproperty){
    properties.push(key)
  }
  let str = properties.join(',')
  let sdate = $('#qBeginTime').val();
  let edate = $('#qEndTime').val();
  if(str!=''&&sdate!=''){
    let headers = new Headers();
    let authToken = localStorage.getItem("token");
    headers.append('Authorization', `token ${authToken}`);
    let options = new RequestOptions({ headers: headers }); 
    this.http.post('http://101.37.24.73:8088/export/gh',{
      device_id:this.deviceId,
      sdate:sdate,   
      edate:edate,              
      parameter:str
    },options).subscribe(res=>{
      //console.log(res.json());
      this.out60d = res.json().result.aaData.url;     
         
      btn60.button('reset');       
 
    },err=>{
      alert('查询失败');
      btn60.button('reset'); 
    })    
  }else{
      alert('请选择参数或者时间');
      btn60.button('reset'); 
  }
}
//该设备的全部
confirmExport(){
  let bt = $("#BeginTime").val();
  let et = $("#EndTime").val();
  if(bt&&et){ 
  //console.log(this.deviceId)   
    this.httpRequest.sendPost('export_queue/push', { 
        device_id:this.deviceId,
        start:bt,
        end:et
    },'op').subscribe(res=>{
      //console.log(res)
      alert(res.msg);     
      this.myModal.hide();
      $("#BeginTime").val('');
      $("#EndTime").val('');  
    },err=>{
      alert('请求失败');
      $("#BeginTime").val('');
      $("#EndTime").val(''); 
    });

  }else{
    alert("请选择好时间段")
  }

}

cansel(){
   $("#BeginTime").val('');
   $("#EndTime").val('');  
}




  initChart(){
    var plotBands = [
      {from: 0.00, to: 0.80, color: '#55BF3B' },
      { from: 0.80,to: 1.50,color: '#DDDF0D'},
      {from: 1.50,to: 2.00,color: '#DF5353'}];
    this.init('angular-gauge1','供气压力',-150,150,0.00,2.00,'压力',0.00,'Mpa',plotBands,(chart)=>{
      this.chart1 = chart;
    });

    plotBands = [
      {from: -20, to: 60, color: '#55BF3B' },
      { from: 60,to:100 ,color: '#DDDF0D'},
      {from:100,to: 150,color: '#DF5353'}];
    this.init('angular-gauge2','排气温度',-150,150,-20,150,'温度',0.0,'℃',plotBands,(chart)=>{
      this.chart2 = chart;
    });

    plotBands = [
      {from: 0, to: 350, color: '#55BF3B' },
      { from: 350,to: 700,color: '#DDDF0D'},
      {from: 700,to:1000,color: '#DF5353'}];
    this.init('angular-gauge3','主机A项电流',-150,150,0,1000,'电流',0.0,'A',plotBands,(chart)=>{
      this.chart3 = chart;
    });
  }


  onEvent(msgs,that){
    let did = msgs.did;
    let msg = msgs.data;
    //console.log(msgs)


    let a = msg.ScrewMachine_State_1.toFixed(2);
    that.updatechart(that.chart1,parseFloat(a));
  
    let b = msg.ScrewMachine_State_2.toFixed(1);
    that.updatechart(that.chart2,parseFloat(b)-30);
 
    let c = msg.ScrewMachine_State_5.toFixed(1);
    that.updatechart(that.chart3,parseFloat(c));

    for(var key in msg){
      $("#"+key).text(msg[key]);

      if(key=="ScrewMachine_State_12" && msg[key]=="0"){
        $("#ScrewMachine_State_12").text('停止');
        $("#ScrewMachine_State_121").removeClass("blue");
        $("#ScrewMachine_State_121").addClass("gray");

      }
      if(key=="ScrewMachine_State_12" && msg[key]=="1"){
        $("#ScrewMachine_State_12").text('运行');
        $("#ScrewMachine_State_121").removeClass("gray");
        $("#ScrewMachine_State_121").addClass("blue");
      }
      if(key=="ScrewMachine_State_11" && msg[key]=="0"){
        $("#ScrewMachine_State_11").text('卸载');
        $("#ScrewMachine_State_111").removeClass("blue");
        $("#ScrewMachine_State_111").addClass("gray");

      }
      if(key=="ScrewMachine_State_11" && msg[key]=="1"){
        $("#ScrewMachine_State_11").text('加载');
        $("#ScrewMachine_State_111").removeClass("gray");
        $("#ScrewMachine_State_111").addClass("blue");

      }
      for(var i=13;i<20;i++){
        var key1 = "ScrewMachine_State_" + i;
        if(key == key1 && msg[key]=="1"){
          $("#"+key).text("");
          $("#"+key).removeClass("gray");
          $("#"+key).addClass("red");
        }
        if(key == key1 && msg[key]=="0"){
          $("#"+key).text("");
          $("#"+key).removeClass("red");
          $("#"+key).addClass("gray");
        }
      }

      for( var l = 20;l<24;l++){
        var key4 = "ScrewMachine_State_" + l;
        if(key ==key4 && msg[key]=="1"){
          $("#"+key).text("");
          $("#"+key).removeClass("gray");
          $("#"+key).addClass("blue");
        }
        if(key ==key4 && msg[key]=="0"){
          $("#"+key).text("");
          $("#"+key).removeClass("blue");
          $("#"+key).addClass("gray");
        }
      }

      for(var j=29;j<33;j++){
        var key2 = "ScrewMachine_State_" + j;
        if(key == key2 && msg[key]=="1"){
          $("#"+key).text("");
          $("#"+key).removeClass("gray");
          $("#"+key).addClass("red");
        }
        if(key == key2 && msg[key]=="0"){
          $("#"+key).text("");
          $("#"+key).removeClass("red");
          $("#"+key).addClass("gray");
        }
      }



      for(var m=24;m<29;m++){
        var key3 = "ScrewMachine_State_" + m;
        if(key == key3 && msg[key]=="1"){
          $("#"+key).text("");
          $("#"+key).removeClass("gray-box");
          $("#"+key).addClass("orange-box");
        }
        if(key == key3 && msg[key]=="0"){
          $("#"+key).text("");
          $("#"+key).removeClass("orange-box");
          $("#"+key).addClass("gray-box");
        }
      }
    }

  }

  updatechart(chart,data){
    if (!chart.renderer.forExport) {
      let point = chart.series[0].points[0];
      point.update(data);
    }
  }

  init(id,text,startAg,endAg,min,max,name,initVal,subfix,pb,cb){
    $('#' + id).highcharts({

        chart: {
          type: 'gauge',
          plotBackgroundColor: null,
          plotBackgroundImage: null,
          plotBorderWidth: 0,
          plotShadow: false
        },
        title:{
          text: ''

        },
        pane: {
          startAngle: startAg,
          endAngle: endAg,
          background: [{
            backgroundColor: {
              linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
              stops: [
                [0, '#FFF'],
                [1, '#333']
              ]
            },
            borderWidth: 0,
            outerRadius: '109%'
          }, {
            backgroundColor: {
              linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
              stops: [
                [0, '#333'],
                [1, '#FFF']
              ]
            },
            borderWidth: 1,
            outerRadius: '107%'
          }, {

          }, {
            backgroundColor: '#DDD',
            borderWidth: 0,
            outerRadius: '105%',
            innerRadius: '103%'
          }]
        },

        yAxis: {
          min: min,
          max: max,
          minorTickInterval: 'auto',
          minorTickWidth: 1,
          minorTickLength: 10,
          minorTickPosition: 'inside',
          minorTickColor: '#666',
          tickPixelInterval: 30,
          tickWidth: 2,
          tickPosition: 'inside',
          tickLength: 10,
          tickColor: '#666',
          labels: {
            step: 2,
            rotation: 'auto'
          },
          title: {
            text: subfix
          },
          plotBands: pb
        },

        series: [{
          name: name,
          data: [initVal],
          tooltip: {
            valueSuffix: ' '+ subfix +' '
          }
        }]

      },
      function (chart) {
        cb(chart);
      });
  }


}
